'use strict';

const Service = require('egg').Service;

class field extends Service {
  // 加字段
  async add(table_id, name,type,index, is_search, must_search, show_search) {
    const { app } = this;
    const hasTable = await app.mysql.get('table', { id: table_id });
    if (!hasTable) {
      return;
    }
    const data = {
      table_id,
      name,
      type,
      create_time: Date.now(),
    };
    if (app.validate(index).int()) {
      data.index = index;
    }
    if (app.validate(is_search).int()) {
      data.is_search = is_search;
    }
    if (app.validate(must_search).int()) {
      data.must_search = must_search;
    }
    if (app.validate(show_search).int()) {
      data.show_search = show_search;
    }

    const result = await app.mysql.insert('field', data);
    if (result.affectedRows) {
      return result.insertId;
    }
  }
  // 加字段 批量加
  async addmost(table_id, fields) {
    const { service } = this;
    const fieldList = [];
    for (let i = 0; i < fields.length; i++) {
      const item = fields[i];
      const fieldId = await service.field.add(table_id, item.name,item.type,item.index, item.is_search, item.must_search, item.show_search);
      fieldList.push(fieldId);
    }
    return fieldList.every(i => !!i);
  }

  // 查字段
  async query(table_id) {
    const { app } = this;
    const result = await app.mysql.select('field', {
      where: { table_id },
      orders: [[ 'index', 'desc' ], [ 'id' ]],
    });
    return result;
  }

  // 更新字段
  async update(id, name,type,index, is_search, must_search, show_search) {
    const { app } = this;
    const data = {
      type,
      modify_time: Date.now(),
    };
    if (app.validate(name).hasString()) {
      data.name = name;
    }
    if (app.validate(index).int()) {
      data.index = index;
    }
    if (app.validate(is_search).int()) {
      data.is_search = is_search;
    }
    if (app.validate(must_search).int()) {
      data.must_search = must_search;
    }
    if (app.validate(show_search).int()) {
      data.show_search = show_search;
    }
    const result = await app.mysql.update('field', data, {
      where: { id },
    });
    if (result.changedRows) {
      return true;
    }
  }

  // 删除字段
  async delete(ids) {
    const { app } = this;
    const all = ids.map(i => +i).map(id => {
      return app.mysql.delete('field', { id });
    });
    await Promise.all(all);
    return true;
  }
}

module.exports = field;
